import os

from flask import jsonify, request
from werkzeug.utils import secure_filename

from model import UserConfig, db
from service import UserService, UserConfigService, StudyPlanService, ChatService,NoteService,TranslationService
from tools.dto import Response
from tools.validate import RequestParser


def login():
    parser = RequestParser()
    parser.add_argument('username', type=str, required=True, help='username is required')
    parser.add_argument('password', type=str, required=True, help='password is required')
    args = parser.parse_args()
    service = UserService()
    status, message, result = service.login(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def forget_password():
    parser = RequestParser()
    parser.add_argument('username', type=str, required=True, help='username is required')
    parser.add_argument('email', type=str, required=True, help='email is required')
    parser.add_argument('password', type=str, required=True, help='password is required')
    args = parser.parse_args()
    service = UserService()
    status, message, result = service.forget_password(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def register():
    parser = RequestParser()
    parser.add_argument('username', type=str, required=True, help='username is required')
    parser.add_argument('password', type=str, required=True, help='password is required')
    parser.add_argument('email', type=str, required=True, help='email is required')
    args = parser.parse_args()
    service = UserService()
    status, message, result = service.register(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def update_user_config():
    parser = RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    parser.add_argument('gender', type=str, required=False, help='gender is optional')
    parser.add_argument('bio', type=str, required=False, help='bio is optional')
    parser.add_argument('location', type=str, required=False, help='location is optional')
    parser.add_argument('birth_date', type=str, required=False, help='birth_date is optional')
    parser.add_argument('avatar', type=str, required=False, help='avatar is optional')
    args = parser.parse_args()
    service = UserConfigService()
    status, message, result = service.update_user_config(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def generate_study_plan():
    parser = RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    parser.add_argument('subject', type=str, required=True, help='subject is optional')
    parser.add_argument('goal', type=str, required=True, help='goal is optional')
    parser.add_argument('duration', type=int, required=True, help='duration is optional')
    args = parser.parse_args()
    service = StudyPlanService()
    status, message, result = service.generate_study_plan(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def start_chat():
    parser=RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    args=parser.parse_args()
    service=ChatService()
    status, message, result = service.start_chat(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def chat():
    parser = RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    parser.add_argument('chat_session_id', type=int, required=True, help='chat_session_id is required')
    parser.add_argument('question', type=str, required=True, help='question is required')
    args = parser.parse_args()
    service = ChatService()
    status, message, result = service.chat(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def get_history():
    parser = RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    args = parser.parse_args()
    service = ChatService()
    status, message, result = service.get_history(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def delete_chat():
    parser = RequestParser()
    parser.add_argument('chat_session_id', type=int, required=True, help='chat_session_id is required')
    args = parser.parse_args()
    service = ChatService()
    status, message, result = service.delete_chat(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def search_chat():
    parser = RequestParser()
    parser.add_argument('chat_title', type=int, required=True, help='chat_title is required')
    args = parser.parse_args()
    service = ChatService()
    status, message, result = service.search_chat(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def get_history_detail():
    parser = RequestParser()
    parser.add_argument('chat_session_id', type=int, required=True, help='chat_session_id is required')
    args = parser.parse_args()
    service = ChatService()
    status, message, result = service.get_history_detail(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def save_note():
    parser = RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    parser.add_argument('note_id', type=str, help='note_id is required')
    parser.add_argument('title', type=str, required=True, help='title is required')
    parser.add_argument('content', type=str, required=True, help='content is required')
    parser.add_argument('summary', type=str, required=True, help='summary is required')
    args = parser.parse_args()
    service = NoteService()
    status, message, result = service.save_note(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def search_note():
    parser = RequestParser()
    parser.add_argument('title', type=str, required=True, help='title is required')
    args = parser.parse_args()
    service = NoteService()
    status, message, result = service.search_note(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def delete_note():
    parser = RequestParser()
    parser.add_argument('note_id', type=int, required=True, help='note_id is required')
    args = parser.parse_args()
    service = NoteService()
    status, message, result = service.delete_note(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def get_note():
    parser = RequestParser()
    parser.add_argument('note_id', type=int, required=True, help='note_id is required')
    args = parser.parse_args()
    service = NoteService()
    status, message, result = service.get_note(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def get_all_notes():
    parser = RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    args = parser.parse_args()
    service = NoteService()
    status, message, result = service.get_all_notes(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def update_note():
    parser = RequestParser()
    parser.add_argument('note_id', type=int, required=True, help='note_id is required')
    parser.add_argument('title', type=str, required=True, help='title is required')
    parser.add_argument('content', type=str, required=True, help='content is required')
    parser.add_argument('summary', type=str, required=True, help='summary is required')
    args = parser.parse_args()
    service = NoteService()
    status, message, result = service.update_note(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def  translate_text():
    parser = RequestParser()
    print(request.json)
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    parser.add_argument('source_language', type=str, required=True, help='source_language is required')
    parser.add_argument('target_language', type=str, required=True, help='target_language is required')
    parser.add_argument('original_text', type=str, required=True, help='original_text is required')
    args = parser.parse_args()
    service = TranslationService()
    status, message, result = service.translate_text(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()

def translate_file():
    return None


def generate_summary():
    parser = RequestParser()
    parser.add_argument('content', type=str, required=True, help='content is required')
    args = parser.parse_args()
    service = NoteService()
    status, message, result = service.generate_summary(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def get_user_config():
    parser = RequestParser()
    parser.add_argument('user_id', type=int, required=True, help='user_id is required')
    args = parser.parse_args()
    service = UserConfigService()
    status, message, result = service.get_user_config(args)
    if status:
        return Response("success", message, result).convert_to_dict()
    return Response("failed", message, result).convert_to_dict()


def upload_avatar():
    if 'avatar' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['avatar']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if file:
        filename = secure_filename(file.filename)
        file_path = os.path.join("uploads/avatars", filename)
        file.save(file_path)
        # 保存文件路径到数据库
        user_id = request.headers.get('Authorization').split(' ')[1]  # 假设用户 ID 存储在 token 中
        user_config = UserConfig.query.filter_by(user_id=user_id).first()
        if user_config:
            user_config.avatar = filename
            db.session.commit()
            return jsonify({'message': 'Avatar uploaded successfully', 'filename': filename}), 200
        else:
            return jsonify({'error': 'User config not found'}), 404